package com.example.doipandroidclient;

import android.renderscript.ScriptGroup;
import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyPair;
import java.util.Map;

import endpoint.irpClient.CdiIrpClient;

public class AndroidCdiIrpClient extends CdiIrpClient {

    String url;
    String TAG = "IRP";

    public AndroidCdiIrpClient(KeyPair kp, String clientID, String LHSUrl) {
        super(kp, clientID, LHSUrl);
        url = LHSUrl;
    }

    @Override
    public String resolveFromLHS(String id){
        final String[] result = new String[1];
        String resolveUrl = url + "resolve?identifier=" + id;
        new Thread(() -> {
            HttpURLConnection connection = null;
            BufferedReader reader = null;
            try {
                // 第一步：创建必要的URL对象
                URL httpUrl = new URL(resolveUrl);
                // 第二步：根据URL对象，获取HttpURLConnection对象
                connection = (HttpURLConnection) httpUrl
                        .openConnection();
                // 第三步：为HttpURLConnection对象设置必要的参数（是否允许输入数据、连接超时时间、请求方式）
                connection.setConnectTimeout(10000);
                connection.setReadTimeout(10000);
                connection.setRequestMethod("GET");
                int responseCode = connection.getResponseCode();
                if(responseCode !=200) {
                    //请求成功 获得返回的流
                    info("IRP resolution error: " + responseCode);
                    throw new Exception("IRP resolution error: " + responseCode);
                }
                // 第五步：开始读取服务器返回数据
                result[0] = getStringFromInputStream(connection.getInputStream());
                synchronized (result) {
                    result.notifyAll();
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (connection != null) {//关闭连接
                    connection.disconnect();
                }
            }
        }).start();
        try {
            synchronized (result){
                result.wait();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();

        }
        return result[0];
    }

    @Override
    public String sendPost(final Map<String, String> reqMap, String url){
        final String[] result = new String[1];
        final String urlStr = url;
        //开启线程，发送请求
        new Thread(() -> {
            HttpURLConnection connection = null;
            BufferedReader reader = null;
            try {
                // 第一步：创建必要的URL对象
                URL httpUrl = new URL(urlStr);
                // 第二步：根据URL对象，获取HttpURLConnection对象
                connection = (HttpURLConnection) httpUrl
                        .openConnection();
                // 第三步：为HttpURLConnection对象设置必要的参数（是否允许输入数据、连接超时时间、请求方式）
                connection.setConnectTimeout(10000);
                connection.setReadTimeout(10000);
                connection.setRequestMethod("POST");
                connection.setDoInput(true);
                // 第四步：向服务器写入数据
                OutputStream out = connection.getOutputStream();
                String content = "";
                for(String key:reqMap.keySet()){
                    content = content.concat(key + "=" + reqMap.get(key) + "&");
                }
                Log.d("IRPClient","post information: " + content);
                out.write(content.getBytes());
                out.flush();
                out.close();

                result[0] = getStringFromInputStream(connection.getInputStream());

                synchronized (result) {
                    result.notifyAll();
                }

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (connection != null) {//关闭连接
                    connection.disconnect();
                }
            }
        }).start();

        try {
            synchronized (result){
                result.wait();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return result[0];
    }

    public String getStringFromInputStream(InputStream is) throws IOException {
        String s;
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        final StringBuffer buffer = new StringBuffer();
        String str = null;
        while ((str = reader.readLine()) != null) {
            buffer.append(str);
        }
        reader.close();
        return buffer.toString();
    }


    void debug(String s){
        Log.d(TAG,s);
    }
    void info(String s){
        Log.i(TAG,s);
    }
}
